package com.by.basicweb.filter;

import com.by.basicweb.utils.FromGatewayUtil;
import com.by.basicweb.utils.UnAuthUtil;
import com.by.toolkit.consts.WebGlobalConst;
import com.by.toolkit.enums.FlagEnum;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 无需授权filter
 *
 * @author YanBingHao
 * @since 2024/1/4
 */
@Slf4j
@Order(Integer.MIN_VALUE + 1)
@Component
public class UnAuthFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String requestURI = request.getRequestURI();
        String unAuth = request.getHeader(WebGlobalConst.UN_AUTH);
        String fromGateway = request.getHeader(WebGlobalConst.FROM_GATEWAY);
        log.info("[UnAuthFilter][doFilter] requestURI:[{}] fromGateway:[{}] unAuth:[{}]", requestURI, fromGateway, unAuth);
        UnAuthUtil.getInstance().put(FlagEnum.resolve(StringUtils.isNotBlank(unAuth) && FlagEnum.YES_STR.equals(unAuth)));
        FromGatewayUtil.getInstance().put(FlagEnum.resolve(StringUtils.isNotBlank(fromGateway) && FlagEnum.YES_STR.equals(fromGateway)));
        try {
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            UnAuthUtil.getInstance().remove();
            FromGatewayUtil.getInstance().remove();
        }
    }

}
